#!/bin/bash
#[ $# = 0 ] && TARGET_MP=dopp_angles_tauv_psi0.mp || TARGET_MP=$1
declare input=( "$@" )
for TARGET_MP in ${input[@]}
do
	tmp_mp=tmp.mp
	tmp_tex=tmp.tex
	XAXIS="误差"
	XAXIS_UNIT="米"
	YAXIS="概率"
	CDF="误差累积分布函数"

	#preamble
	grep -v ^% $TARGET_MP |sed 's/\(.*\\documentclass.*\)/\1\n\\usepackage{CJKutf8}/' > $tmp_mp
	mv $tmp_mp $TARGET_MP
	grep -v ^% $TARGET_MP |sed 's/\(.*\\begin{document}.*\)/\1\n\\begin{CJK}{UTF8}{song}/' > $tmp_mp
	mv $tmp_mp $TARGET_MP
	grep -v ^% $TARGET_MP |sed 's/\(.*\\end{document}.*\)/\\end{CJK}\n\1/' > $tmp_mp
	mv $tmp_mp $TARGET_MP
	#\r
	sed  's/\(.*\)\r\(.*\)/\1\\r\2/' $TARGET_MP |sed 's/\(.*\)\r\(.*\)/\1\\r\2/' > $tmp_mp
	mv $tmp_mp $TARGET_MP
	#error/m
	sed  's/\(.*\)error\/m\(.*\)/\1'"$XAXIS"'\/'"$XAXIS_UNIT"'\2/' $TARGET_MP |sed 's/\(.*\)\r\(.*\)/\1\\r\2/' > $tmp_mp
	mv $tmp_mp $TARGET_MP
	#probability
	sed  's/\(.*\)probability\(.*\)/\1'"$YAXIS"'\2/' $TARGET_MP |sed 's/\(.*\)\r\(.*\)/\1\\r\2/' > $tmp_mp
	mv $tmp_mp $TARGET_MP
	#chinese legends
	sed  's/\(.*\)CDF\(.*\)/\1'"$CDF"'\2/' $TARGET_MP |sed 's/\(.*\)\r\(.*\)/\1\\r\2/' > $tmp_mp
	mv $tmp_mp $TARGET_MP
    
	mpost -tex=latex $TARGET_MP

	rm -f $tmp_tex
	tmpfile=`ls "${TARGET_MP%.*}".[0-9]*`
	#tmpfile=`ls "${TARGET_MP%.*}".2`
	echo "\documentclass{article}" >> $tmp_tex
	echo "\usepackage{graphicx}" >> $tmp_tex
	echo "\begin{document}" >> $tmp_tex
	echo "\thispagestyle{empty}" >> $tmp_tex
	echo "\begin{figure}" >> $tmp_tex
	echo "\includegraphics[width=12cm]{$tmpfile}" >> $tmp_tex
	echo "\end{figure}" >> $tmp_tex
	echo "\clearpage" >> $tmp_tex
	echo "\end{document}" >> $tmp_tex
	latex ${tmp_tex%.*} && dvips ${tmp_tex%.*} && ps2eps -f ${tmp_tex%.*}.ps
	mv ${tmp_tex%.*}.eps ${TARGET_MP%.*}.eps
	rm -f ${tmp_tex%.*}.*

	eps2jpg -f ${TARGET_MP%.*}.eps
done
rm -f *.mpx *.[0-9]* *.log

